package com.dxd.dao;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dxd.utils.DbUtil;

public abstract class PublicDao<T> {

	private static final Logger LOG = LoggerFactory.getLogger(PublicDao.class);

	protected Connection con;
	protected PreparedStatement pst;
	protected ResultSet rs;
	protected CallableStatement cs;

	/**
	 * 增删改的通用方法
	 * 
	 * @param sql
	 * @param objs
	 * @return
	 */
	protected int AddOrRemoveOrUpdate(String sql, List<Object> objs) {
		LOG.info(sql, objs);
		try {
			con = DbUtil.getConnection();
			pst = con.prepareStatement(sql);
			if (objs != null && objs.size() > 0) {
				for (int i = 0; i < objs.size(); i++) {
					pst.setObject(i + 1, objs.get(i));
				}
			}
			return pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.closeDB(rs, pst, con);
		}
		return 0;
	}

	/**
	 * 查询单个
	 * 
	 * @param sql
	 * @param objs
	 * @return
	 */
	protected T queryOne(String sql, List<Object> objs) {
		LOG.info(sql, objs);
		try {
			con = DbUtil.getConnection();
			pst = con.prepareStatement(sql);
			if (objs != null && objs.size() > 0) {
				for (int i = 0; i < objs.size(); i++) {
					pst.setObject(i + 1, objs.get(i));
				}
			}
			rs = pst.executeQuery();
			return result(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.closeDB(rs, pst, con);
		}
		return null;
	}

	/**
	 * 查询总条数
	 * 
	 * @param sql
	 * @param objs
	 * @return
	 */
	protected int queryCount(String sql, List<Object> objs) {
		LOG.info(sql, objs);
		try {
			con = DbUtil.getConnection();
			pst = con.prepareStatement(sql);
			if (objs != null && objs.size() > 0) {
				for (int i = 0; i < objs.size(); i++) {
					pst.setObject(i + 1, objs.get(i));
				}
			}
			rs = pst.executeQuery();
			if (rs.next()) {
				return rs.getInt("count");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.closeDB(rs, pst, con);
		}
		return 0;
	}

	/**
	 * 查询多个
	 * 
	 * @param sql
	 * @param objs
	 * @return
	 */
	protected List<T> queryList(String sql, List<Object> objs) {
		LOG.info(sql, objs);
		try {
			con = DbUtil.getConnection();
			pst = con.prepareStatement(sql);
			if (objs != null && objs.size() > 0) {
				for (int i = 0; i < objs.size(); i++) {
					pst.setObject(i + 1, objs.get(i));
				}
			}
			rs = pst.executeQuery();

			return results(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.closeDB(rs, pst, con);
		}
		return null;
	}

	protected abstract T result(ResultSet rs) throws SQLException;

	protected abstract List<T> results(ResultSet rs) throws SQLException;
}
